<template>
  <view class="store-manage">
    <!-- 顶部导航栏 -->
    <view class="header">
      <view class="back-icon" @click="goBack">
        <image src="/static/index/returnIcon.png" mode="widthFix" class="back-icon-box"></image>
      </view>
      <view class="title">库存管理</view>
      <view class="search-icon" @click="toSearch">
        <image src="/static/index/union.png" mode="widthFix" class="search-icon-box"></image>
      </view>
    </view>

    <!-- 切换标签 -->
    <view class="tab-box">
      <view class="tab-container">
        <view class="tab-item" :class="{ active: currentTab == 0 }" @click="switchTab(0)">
          可视化查看
          <view class="active-line" v-if="currentTab == 0"></view>
        </view>
        <view class="tab-item" :class="{ active: currentTab == 1 }" @click="switchTab(1)">
          列表查看
          <view class="active-line" v-if="currentTab === 1"></view>
        </view>
      </view>

    </view>

    <!-- 可视化查看 -->
    <view class="aisle-container" v-if="currentTab == 0">
      <uv-scroll-list>
        <view class="aisle-grid">
          <view v-for="(item, index) in dataList" :key="index" class="aisle-row">
            <view v-for="(i, j) in item" :key="j" class="aisle-item" @click="handleReplenish(i)"
              :class="{'success': Number(i.inventory) - Number(i.threshold) > 0 &&i.medicineName, 'warning': Number(i.inventory) - Number(i.threshold) <= 0&&i.medicineName, 'danger': Number(i.inventory) == 0&&i.medicineName,'grey':!i.medicineName}">
              <view class="aisle-tag"
                :class="{'success': Number(i.inventory) - Number(i.threshold) > 0&&i.medicineName, 'warning': Number(i.inventory) - Number(i.threshold) <= 0&&i.medicineName, 'danger': Number(i.inventory) == 0&&i.medicineName,'grey':!i.medicineName}">
                {{i.slotName||''}}
              </view>
              <view class="aisle-info" v-show="i.medicineName">
                <view class="product-name">{{ i.medicineName || '-' }}</view>
                <view class="product-code">{{ i.barCode || '-' }}</view>
                <view class="stock-info"
                  :class="{'success': Number(i.inventory) - Number(i.threshold) > 0, 'warning': Number(i.inventory) - Number(i.threshold) <= 0, 'danger': Number(i.inventory) == 0}">
                  库存数量 {{i.inventory || 0}}</view>
              </view>
            </view>
          </view>
        </view>
      </uv-scroll-list>
    </view>

    <!-- 列表查看 -->
    <view class="list-container" v-if="currentTab == 1">
      <medicine :listData="dataListRight" @replenish="handleReplenish" />
    </view>

    <view class="back-arm">
      <view class="back-arm-icon" @click="backArm">
        <image src="/static/index/back.png" mode="widthFix" class="back-arm-icon-box"></image>
        <text>收回机械臂</text>
      </view>
      <view class="back-Right" @click="resetArm">
        <image src="/static/index/backRight.png" mode="widthFix" class="back-arm-icon-box"></image>
        <text>复位</text>
      </view>
    </view>
    <!-- 加载更多 -->
    <view style="width: 93.5%;margin: -20rpx auto 0;background: #fff;">
      <uv-load-more v-if="currentTab == 1" :status="status" line height="160" paddingBottom="130" />
    </view>

    <medicine-dialogs ref="medicineDialogs" :medicineInfo="medicineInfo" @getSupply="handleGetSupply" />
  </view>
</template>

<script setup>
  import {
    ref
  } from 'vue'
  import {
    onLoad,
    onPullDownRefresh,
    onReachBottom,
    onShow
  } from '@dcloudio/uni-app'
  import medicine from '@/components/medicine/index.vue'
  import {
    getSlotLeft,
    getSlotRight,
    retract,
    refillMedicine,
  } from '@/api/storeManage.js'
  import {
    changeInfo
  } from '@/utils/lodash.js'
  import MedicineDialogs from '@/components/medicineDialogs/index.vue'

  const currentTab = ref(0)
  const medicineDialogs = ref(null)

  const status = ref("loadmore") // 加载状态
  const query = ref({
    pageNum: 1,
    pageSize: 10,
    cabinetId: uni.getStorageSync('machineInfo').id
  })

  const total = ref(0)
  const dataList = ref([])
  const dataListRight = ref([])
  const cabinetId = ref(uni.getStorageSync('machineInfo').id)
  const medicineInfo = ref({})

  // 切换标签
  const switchTab = (tab) => {
    currentTab.value = tab
    query.value.pageNum = 1
    if (currentTab.value == 0) {
      getList()
    } else {
      getListRight()
    }
    // 滑动到顶部
    uni.pageScrollTo({
      scrollTop: 0,
      duration: 0
    })
  }

  // 搜索
  const toSearch = () => {
    uni.navigateTo({
      url: '/pages/storeManage/search'
    })
  }
  // 返回上一页
  const goBack = () => {
    uni.navigateBack()
  }
  onLoad(() => {
    const machineInfo = uni.getStorageSync('machineInfo')
    query.value.cabinetId = machineInfo.id

  })
  // 处理补药按钮点击
  const handleReplenish = (item) => {
    if (!item.medicineName) return
    medicineInfo.value = item
    medicineDialogs.value.openStockDialog()
  }

  const handleGetSupply = async (data, resolve) => {
    const res = await refillMedicine(data)
    if (res.code == 200) {
      uni.showToast({
        title: '补药成功',
      })
      resolve()
      if (currentTab.value == 0) {
        getList()
      } else {
        getListRight()
      }

    }
  }
  // 获取货架列表
  const getList = async () => {
    try {
      const res = await getSlotLeft(query.value)
      if (res.code === 200) {
        dataList.value = res.data || []
      }
    } catch (error) {
      console.log(error)
    }
  }

  // 获取货架列表
  const getListRight = async () => {
    try {
      status.value = 'loading'
      const res = await getSlotRight(query.value)
      if (res.code == 200) {
        dataListRight.value = query.value.pageNum == 1 ? res.rows : dataListRight.value.concat(res.rows)
        total.value = res.total
        console.log(dataListRight.value.length, 'length------------', total.value)
        status.value = dataListRight.value.length == total.value ? 'noMore' : 'loadmore'
        dataListRight.value = dataListRight.value.map(item => {
          return {
            ...item,
            status: Number(item.inventory) == 0 ? 'danger' : Number(item.inventory) - Number(
              item.threshold) > 0 ? 'success' : 'warning'
          }
        })
      }
    } catch (error) {
      console.log(error)
    }
  }

  // 上拉加载更多
  onReachBottom(() => {
    console.log(status.value, '上拉加载更多')
    if (status.value == 'loadmore' && currentTab.value == 1) {
      query.value.pageNum++
      getListRight()
    }
  })

  const backArm = async () => {
    const res = await changeInfo({
      cabinetId: cabinetId.value
    }, '/applet/inventory/retract')
    if (res.code == 200) {
      uni.showToast({
        title: '收回机械臂成功',
        icon: 'none'
      })
    }
  }
  const resetArm = async () => {
    const res = await changeInfo({
      cabinetId: cabinetId.value
    }, '/applet/inventory/reset')
    if (res.code == 200) {
      uni.showToast({
        title: res.msg,
        icon: 'none'
      })
    }
  }


  // 下拉刷新
  onPullDownRefresh(() => {
    console.log('下拉刷新')
    if (currentTab.value == 1) {
      query.value.pageNum = 1
      getListRight()
    }
  })

  // 打开药品管理弹框
  const openMedicineDialog = (item) => {

    medicineDialogs.value.openStockDialog()
  }

  onShow(() => {
    getList()
  })
</script>

<style lang="scss" scoped>
  .aisle-container {
    margin: 24rpx;
    background: #fff;
    margin-top: 338rpx;
    padding-bottom: 90rpx;
    padding: 24rpx;
    overflow: hidden;

    .aisle-grid {
      width: 100%;

      .aisle-row {
        display: flex;
        flex-wrap: nowrap;
        margin-bottom: 25rpx;
        overflow-x: auto;

        .aisle-item {
          flex: 0 0 256rpx;
          background: #fff;
          border-radius: 12rpx;
          padding: 25rpx;
          margin-right: 20rpx;
          position: relative;
          min-height: 280rpx;
          background-size: cover;
          background-position: center;
          background-repeat: no-repeat;
          border: 2rpx solid #f0efef;

          &:last-child {
            margin-right: 0;
          }

          &.success {
            background-image: url('/static/index/bg_1.png');
          }

          &.warning {
            background-image: url('/static/index/bg_3.png');
          }

          &.danger {
            background-image: url('/static/index/bg_2.png');
          }

          &.grey {
            background: url('/static/index/cadr.png') no-repeat;
            background-size: 70%;
            background-position: center;
            width: 100%;
            height: 100%;
          }

          .aisle-tag {
            display: inline-block;
            padding: 8rpx 20rpx;
            font-size: 24rpx;
            color: #fff;
            border-radius: 50rpx;
            margin-bottom: 16rpx;
            font-weight: 500;
            position: relative;
            z-index: 1;

            &.success {
              background: #07c160;
            }

            &.warning {
              background: #ff9900;
            }

            &.danger {
              background: #ff4d4f;
            }

            &.grey {
              background: #F0F1F4;
              color: #9CA3AF;
            }
          }

          .aisle-info {
            position: relative;
            z-index: 1;
            padding: 20rpx;
            border-radius: 8rpx;

            .product-name {
              font-size: 28rpx;
              color: #333;
              margin-bottom: 14rpx;
              margin-top: 24rpx;
              font-weight: 600;
              white-space: nowrap;
              overflow: hidden;
              text-overflow: ellipsis;
            }

            image {
              width: 260rpx;
              height: 200rpx;
            }

            .product-code {
              font-size: 24rpx;
              color: #999;
              margin-bottom: 32rpx;
              overflow: hidden;
              text-overflow: ellipsis;
              white-space: nowrap;
              display: block;
              width: 220rpx;
            }

            .stock-info {
              font-size: 26rpx;

              &.success {
                color: #07c160;
              }

              &.warning {
                color: #ff9900;
              }

              &.danger {
                color: #ff4d4f;
              }
            }
          }
        }
      }
    }
  }

  .list-container {
    flex: 1;
    background: #C0E5F8;
    padding: 24rpx;
    padding-top: 328rpx;
    padding-bottom: 0;
  }

  .store-manage {
    min-height: 100vh;
    background: #C0E5F8;
    overflow: scroll;

    .header {
      height: 148rpx;
      background: #C0E5F8;
      display: flex;
      align-items: center;
      padding: 50rpx 30rpx 0;
      position: relative;
      position: fixed;
      top: 0;
      left: 0;
      right: 0;
      z-index: 100;

      .back-icon {
        .back-icon-box {
          width: 16rpx;
          height: 16rpx;
        }
      }

      .title {
        position: absolute;
        left: 50%;
        transform: translateX(-50%);
        font-size: 32rpx;
        font-weight: 500;
        color: #333;
      }

      .search-icon {
        position: absolute;
        right: 30rpx;

        .search-icon-box {
          width: 32rpx;
          height: 36rpx;
        }
      }
    }

    .tab-box {
      background: #C0E5F8;
      position: fixed;
      top: 170rpx;
      left: 0;
      right: 0;
      z-index: 100;
      padding-top: 30rpx;
    }

    .tab-container {
      margin-top: 2rpx;
      display: flex;
      padding: 0 60rpx 0;
      border-bottom: 1rpx solid #f5f5f5;
      margin: 24rpx;
      background: #fff;
      border-top-left-radius: 50rpx;
      border-top-right-radius: 50rpx;
      padding: 20rpx;
      margin-bottom: 0rpx;

      .tab-item {
        flex: 1;
        text-align: center;
        font-size: 28rpx;
        color: #666;
        padding: 20rpx 0;
        position: relative;

        &.active {
          color: #3B82F6;
          font-weight: 500;
        }

        .active-line {
          position: absolute;
          bottom: 0;
          left: 50%;
          transform: translateX(-50%);
          width: 160rpx;
          height: 4rpx;
          background: #3B82F6;
          border-radius: 2rpx;
        }
      }
    }

    .medicine-list {
      .medicine-item {
        background-color: #fff;
        padding: 20rpx;
        margin-bottom: 20rpx;
        border-radius: 8rpx;

        .position {
          display: inline-block;
          background-color: #00aa00;
          color: #fff;
          padding: 4rpx 12rpx;
          border-radius: 4rpx;
          margin-right: 20rpx;
        }

        .name {
          font-weight: bold;
        }

        .stock {
          float: right;
          color: #00aa00;
        }
      }
    }

    .back-arm {
      position: fixed;
      bottom: 0;
      left: 3.2%;
      right: 0;
      z-index: 900;
      padding: 20rpx 40rpx;
      background: #fff;
      color: #fff;
      font-size: 28rpx;
      font-weight: 500;
      height: 70rpx;
      width: 83%;
      display: flex;
      align-items: center;
      justify-content: space-between;

      .back-arm-icon {
        background: #3B82F6;
        width: 45%;
        text-align: center;
        border-radius: 50rpx;
        display: flex;
        align-items: center;
        justify-content: center;
        margin: 0 auto;
        height: 73rpx;
        line-height: 73rpx;

        image {
          margin-right: 6rpx;
          width: 30rpx;
          height: 30rpx;
        }
      }

      .back-Right {
        background: #fff;
        width: 43%;
        text-align: center;
        border-radius: 50rpx;
        display: flex;
        align-items: center;
        justify-content: center;
        margin: 0 auto;
        height: 72rpx;
        line-height: 72rpx;
        box-shadow: 0 0 2rpx rgba(0, 0, 0, 0.3);
        color: #9CA3AF;

        image {
          margin-right: 6rpx;
          width: 30rpx;
          height: 30rpx;
        }
      }
    }
  }
</style>